<script setup lang="ts">
import { watch, computed } from 'vue'
import { theme } from 'ant-design-vue'
import { RouterView } from 'vue-router'
import andtvCN from 'ant-design-vue/es/locale/zh_CN'
import { zhCN as nuCN, dateZhCN, darkTheme } from 'naive-ui'
import { storeToRefs } from 'pinia'
import { useGlobalStore } from '@/stores/global'
import { lighten } from '@/utils/color'
import $config from '@/config'

// 全局存储
const globalStore = useGlobalStore()
const { isDarkTheme } = storeToRefs(globalStore)

const themeColor = computed(() => {
  return isDarkTheme.value ? $config.darkThemeColor : $config.themeColor
})

// 设置 vh 高度单位
// 解决部分手机端浏览器由于安全区域导致 css vh 与实际不符的问题
function setViewportHeight() {
  const vh = window.innerHeight * 0.01
  document.documentElement.style.setProperty('--vh', `${vh}px`)
}

window.addEventListener('load', setViewportHeight)
window.addEventListener('resize', setViewportHeight)

// 键盘弹出处理
const originalHeight = window.innerHeight
window.addEventListener('resize', () => {
  const currentHeight = window.innerHeight
  if (currentHeight < originalHeight) {
    document.documentElement.style.setProperty('--vh', `${currentHeight * 0.01}px`)
  } else {
    document.documentElement.style.setProperty('--vh', `${originalHeight * 0.01}px`)
  }
})

// 禁止移动端缩放页面
document.addEventListener('gesturestart', function (event) {
  event.preventDefault()
})

// 设置标题
document.title = $config.title

// 监听：暗黑主题
watch(
  isDarkTheme,
  (value) => {
    if (value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <a-config-provider
    :locale="andtvCN"
    :theme="{
      algorithm: isDarkTheme ? theme.darkAlgorithm : theme.defaultAlgorithm,
      token: {
        colorPrimary: themeColor,
      },
    }"
  >
    <n-config-provider
      :locale="nuCN"
      :date-locale="dateZhCN"
      :theme="isDarkTheme ? darkTheme : null"
      :theme-overrides="{
        common: {
          primaryColor: themeColor,
          primaryColorHover: lighten(themeColor, 0.3),
          primaryColorPressed: lighten(themeColor, 0.2),
          primaryColorSuppl: lighten(themeColor, 0.3),
        },
      }"
    >
      <RouterView class="h-100vh" />
    </n-config-provider>
  </a-config-provider>
</template>
